package com.commerceE.managedBean;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.StreamedContent;
import org.primefaces.model.UploadedFile;

import com.commerceE.common.exception.ServiceException;
import com.commerceE.domain.Images;
import com.commerceE.domain.Products;
import com.commerceE.service.ImageService;
import com.commerceE.util.SpringUtil;

@ManagedBean(name = "productImageBean")
@RequestScoped
public class ProductImageBean {

	@ManagedProperty(value = "#{adminHomeBean}")
	private AdminHomeBean adminHomeBean;

	private ImageService imageService;

	private List<Images> loadedImages;

	private Images selectedImage;
	
	private Images editedImage = new Images();

	private StreamedContent listImage = null;

	private Products selectedProduct = null;

	private Long image_selectedProductId = null;

	ExternalContext externalContext = FacesContext.getCurrentInstance()
			.getExternalContext();
	Map<String, Object> sessionMap = externalContext.getSessionMap();

	public ProductImageBean() {
		imageService = (ImageService) SpringUtil.getBeanById("imageService");
		loadedImages = (List<Images>)sessionMap.get("loadedImages");
	}

	public void addImageInput() {
		if (selectedProduct == null) {
			FacesMessage msg = new FacesMessage("Please select 1 row first!",
					"");
			FacesContext.getCurrentInstance().addMessage(null, msg);
		} else {
			image_selectedProductId = selectedProduct.getProductId();
			sessionMap.put("image_selectedProductId", image_selectedProductId);
			loadedImages = imageService.getImagesByInstanceId(image_selectedProductId);
			sessionMap.put("loadedImages", loadedImages);
			adminHomeBean.setCenterPage("/xhtml/productImages.xhtml");
		}
	}

	public void saveUploadedImages() {
		if (loadedImages != null) {
			String filenames = "";
			for (Images file : loadedImages) {
				filenames = filenames + ", " + file.getPath();
			}
			FacesMessage msg = new FacesMessage("Succesful", filenames
					+ "  is saved.");
			FacesContext.getCurrentInstance().addMessage(null, msg);
		}
	}

	public void handleFileUpload(FileUploadEvent event) {
		UploadedFile file = event.getFile();
		image_selectedProductId = (Long) sessionMap
				.get("image_selectedProductId");
		String imageName = image_selectedProductId + "_" + file.getFileName();
		try {
			FileOutputStream fileOutputStream = new FileOutputStream(
					externalContext.getRealPath("//image_upload") + "//"
							+ imageName, true);

			byte[] buffer = new byte[1024];
			int bulk;
			InputStream inputStream = file.getInputstream();
			while (true) {
				bulk = inputStream.read(buffer);
				if (bulk < 0) {
					break;
				}
				fileOutputStream.write(buffer, 0, bulk);
				fileOutputStream.flush();
			}

			fileOutputStream.close();
			inputStream.close();

			FacesMessage msg = new FacesMessage("Successful",
					file.getFileName() + " is uploaded.");
			FacesContext.getCurrentInstance().addMessage(null, msg);

		} catch (IOException e) {
			e.printStackTrace();
			FacesMessage error = new FacesMessage(
					"The files were not uploaded!");
			FacesContext.getCurrentInstance().addMessage(null, error);
		}
		Images image = new Images();
		image.setPath(imageName);
		image.setDefaultFlag(false);
		image.setDisplayOrder(10);
		image.setInstanceId(image_selectedProductId);
		try {
			imageService.insertImage(image);
		} catch (ServiceException e) {
			e.printStackTrace();
		}
		loadedImages = imageService.getImagesByInstanceId(image_selectedProductId);
		sessionMap.put("loadedImages",loadedImages);
	}

	public void onEditImageInput() {
		if(selectedImage==null){
			FacesMessage msg = new FacesMessage("Please select image . ", "");
			FacesContext.getCurrentInstance().addMessage(null, msg);
		} else{
			editedImage = new Images();
			editedImage.setImageId(selectedImage.getImageId());
			editedImage.setInstanceId(selectedImage.getInstanceId());
			editedImage.setDefaultFlag(selectedImage.getDefaultFlag());
			editedImage.setDisplayOrder(selectedImage.getDisplayOrder());
			editedImage.setPath(selectedImage.getPath());
			editedImage.setType(selectedImage.getType());
		}
	}
	
	public void onEditImageSubmit() {
		try {
			imageService.updateImage(editedImage);
			image_selectedProductId = (Long)sessionMap.get("image_selectedProductId");
			loadedImages = imageService.getImagesByInstanceId(image_selectedProductId);
			sessionMap.put("loadedImages", loadedImages);
		} catch (ServiceException e) {
			e.printStackTrace();
		}
	}
	

	public void onImageDelete() {
		if (selectedImage == null) {
			FacesMessage msg = new FacesMessage("Please select image . ", "");
			FacesContext.getCurrentInstance().addMessage(null, msg);
		} else {
			try {
				imageService.deleteImage(selectedImage.getImageId());
				loadedImages = (List<Images>) sessionMap.get("loadedImages");
				loadedImages.remove(selectedImage);
			} catch (ServiceException e) {
				e.printStackTrace();
			}
		}
	}

	public AdminHomeBean getAdminHomeBean() {
		return adminHomeBean;
	}

	public void setAdminHomeBean(AdminHomeBean adminHomeBean) {
		this.adminHomeBean = adminHomeBean;
	}

	public ImageService getImageService() {
		return imageService;
	}

	public void setImageService(ImageService imageService) {
		this.imageService = imageService;
	}

	public List<Images> getLoadedImages() {
		return loadedImages;
	}

	public void setLoadedImages(List<Images> loadedImages) {
		this.loadedImages = loadedImages;
	}

	public Images getSelectedImage() {
		return selectedImage;
	}

	public void setSelectedImage(Images selectedImage) {
		this.selectedImage = selectedImage;
	}

	public StreamedContent getListImage() {
		return listImage;
	}

	public void setListImage(StreamedContent listImage) {
		this.listImage = listImage;
	}

	public Products getSelectedProduct() {
		return selectedProduct;
	}

	public void setSelectedProduct(Products selectedProduct) {
		this.selectedProduct = selectedProduct;
	}

	public Long getImage_selectedProductId() {
		return image_selectedProductId;
	}

	public void setImage_selectedProductId(Long image_selectedProductId) {
		this.image_selectedProductId = image_selectedProductId;
	}

	public Images getEditedImage() {
		return editedImage;
	}

	public void setEditedImage(Images editedImage) {
		this.editedImage = editedImage;
	}
	
	

}
